<template>
  <div class="leads">
    <div class="tableConter">
      <el-table class="tableBox" :data="tableData" v-loading="loading">
        <el-table-column label="学员姓名" width="140">
          <template #default="scope">
            <span
              @click="toDetail(scope.row)"
              class="active"
              :title="scope.row.student_name"
            >
              {{ scope.row.student_name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="性别" prop="student_sex"> </el-table-column>

        <el-table-column label="关系" prop="relation"> </el-table-column>
        <el-table-column label="联系电话" prop="student_phone" width="170">
        </el-table-column>
        <el-table-column label="班级" class-name="classes" width="240">
          <template #default="scope">
            <span v-for="(item, idx) in scope.row.student_classes" :key="idx">
              {{ item }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="老师" width="150" class-name="teachers">
          <template #default="scope">
            <span v-for="(item, idx) in scope.row.student_teachers" :key="idx">
              {{ item }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="累计积分" prop="total"> </el-table-column>
        <el-table-column label="剩余积分" prop="balance"> </el-table-column>
        <el-table-column label="操作" :width="'180'">
          <template #default="scope">
            <el-button type="text" @click="operate(scope.row, 1)"
              >增加积分</el-button
            >
            <el-button
              type="text"
              @click="operate(scope.row, 2)"
              :disabled="scope.row.balance <= 0"
              >扣除积分</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        class="laypage"
        v-model:page-size="pageSize"
        layout="prev, pager, next, total,slot"
        :total="Number(tableCount)"
        v-model:currentPage="currentPage"
        @current-change="pageChange"
        @prev-click="pageChange"
        @next-click="pageChange"
      />
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :title="`${title}积分`"
      :before-close="handleClose"
    >
      <div class="personal_info">
        <span>学员姓名：{{ student_name }}</span
        ><span>当前积分：{{ balance }}</span>
      </div>
      <el-form :model="form" label-width="100px" ref="formRef">
        <el-form-item
          :label="`${title}积分`"
          prop="score"
          :rules="[
            {
              required: true,
              message: `请填写${title}积分`,
              trigger: 'blur',
            },
            {
              pattern: /^[0-9]\d*$/,
              message: '只能输入整数',
            },
          ]"
        >
          <el-input
            v-model="form.score"
            :placeholder="`请填写${title}积分`"
            type="number"
          />
        </el-form-item>
        <el-form-item
          :label="`${title}原由`"
          prop="reason"
          :rules="[
            {
              required: true,
              message: `请填写${title}原由`,
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            v-model="form.reason"
            type="text"
            :placeholder="`请填写${title}原由`"
          />
        </el-form-item>
        <el-form-item
          label="时间"
          :rules="[
            {
              required: true,
              message: `请选择时间`,
              trigger: 'change',
            },
          ]"
          prop="show_time"
        >
          <el-date-picker
            v-model="form.show_time"
            type="date"
            placeholder="请选择时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(formRef)">取消</el-button>
          <el-button type="primary" @click="sure(formRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogTableVisible"
      :title="`学员姓名：${userName}`"
      :before-close="tableClose"
    >
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="学情" name="学情">
          <div class="weekSelect">
            <label>week：</label>
            <el-select
              v-model="weekValue"
              placeholder="请选择"
              @change="weekChange"
            >
              <el-option
                v-for="item in weeksList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
          <el-table :data="weekData">
            <el-table-column :label="`第${weekValue}周`" align="center">
              <el-table-column type="index" width="70" label="序号">
              </el-table-column>
              <el-table-column property="book_title" label="书名" width="125" />
              <el-table-column label="类型">
                <template #default="scope">
                  <span>{{ scope.row.extensive ? "精读" : "泛读" }}</span>
                </template>
              </el-table-column>
              <el-table-column property="word" label="词汇" />
              <el-table-column property="explain" label="讲解">
              </el-table-column>
              <el-table-column property="read" label="阅读"> </el-table-column>
              <el-table-column property="follow" label="跟读">
              </el-table-column>
              <el-table-column property="practice" label="练习">
              </el-table-column>
              <el-table-column property="share" label="分享"> </el-table-column>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="积分详情" name="积分详情">
          <div class="personal_info">
            <span>累计获得：{{ detail_total }}</span
            ><span>剩余：{{ detail_balance }}</span>
          </div>
          <div>
            <label>积分类型：</label>
            <el-select
              v-model="value"
              placeholder="请选择积分类型"
              @change="scoreChange"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <el-table :data="gridData">
            <el-table-column property="show_time" label="时间" />
            <el-table-column label="积分变化">
              <template #default="scope">
                <span>{{
                  scope.row.amount > 0
                    ? "+" + scope.row.amount
                    : scope.row.amount
                }}</span>
              </template>
            </el-table-column>
            <el-table-column property="content" label="原由" />
          </el-table>
          <el-pagination
            background
            class="laypage"
            v-model:page-size="pageSize1"
            layout="prev, pager, next, total,slot"
            :total="Number(tableCount1)"
            v-model:currentPage="currentPage1"
            @current-change="pageChange1"
            @prev-click="pageChange1"
            @next-click="pageChange1"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import { toRefs, getCurrentInstance, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
export default {
  name: "IntegralDetails",
  setup() {
    const proxy = getCurrentInstance().appContext.config.globalProperties;
    const router = useRouter();
    let formRef = ref(null); //定义表单ref

    /**
     * 计算今日日期
     */
    var today = new Date();
    today.setTime(today.getTime());
    var year = today.getFullYear();
    var month =
      today.getMonth() + 1 > 10
        ? today.getMonth() + 1
        : "0" + (today.getMonth() + 1);
    var date = today.getDate() > 10 ? today.getDate() : "0" + today.getDate();
    /**
     * 积分类型下拉框
     */
    let options = [
      {
        value: 0,
        label: "全部",
      },
      {
        value: 1,
        label: "获得",
      },
      {
        value: 2,
        label: "消耗",
      },
    ];
    let dataObj = reactive({
      form: {
        //增加或扣除积分表单
        score: "",
        reason: "",
        show_time: year + "-" + month + "-" + date,
      },
      currentPage: 1, //当前页码
      loading: false, //是否loading
      tableCount: null, //table总数
      pageSize: 10, //一页展示几个
      tableData: [], //表单数据
      dialogFormVisible: false, //是否展示增加积分弹窗
      title: "", //增加或者扣除文案
      student_name: "", //增加或扣除积分当前学生姓名
      balance: "", //增加或扣除积分当前学生积分
      user_id: "", //增加或扣除积分当前学生id
      url: "", //增加还是扣除请求路径
      dialogTableVisible: false, //详情弹框是否显示
      gridData: [], //积分详情表格
      userName: "", //详情用户名
      value: 0, //详情下拉框值
      options: options, //详情下拉框选项
      detail_total: "", //详情累计积分
      detail_balance: "", //详情剩余积分
      weeksList: [],
      weekValue: 0,
      weekData: [],
      activeName: "学情",
      pageSize1: 10,
      currentPage1: 1,
      tableCount1: null,
    });
    /**
     * 表格数据
     */
    let assignmentData = () => {
      dataObj.loading = true;
      let parmes = {};
      if (router.currentRoute.value.query.teacher_id) {
        parmes = {
          teacher_id: router.currentRoute.value.query.teacher_id,
        };
      } else {
        parmes = {
          page: dataObj.currentPage,
        };
      }
      proxy.$https
        .get("/api/v1/student/summary", parmes)
        .then((res) => {
          dataObj.loading = false;
          if (!res.code) {
            dataObj.tableData = res.data.data ? res.data.data : [];
            dataObj.tableCount = res.data.total;
          } else {
            dataObj.tableData = [];
            dataObj.tableCount = 0;
          }
        })
        .catch(() => {
          dataObj.tableData = [];
          dataObj.tableCount = 0;
          dataObj.loading = false;
        });
    };
    let getWeekData = () => {
      proxy.$https
        .get("/api/v1/student/learn", {
          user_id: dataObj.user_id,
          // level_type: dataObj.radio,
          week: dataObj.weekValue,
        })
        .then((res) => {
          if (res.code == 0) {
            dataObj.weekData = res.data;
          }
        });
    };
    let getWeeksList = () => {
      proxy.$https
        .get("/api/v1/student/weeks", {
          user_id: dataObj.user_id,
          // level_type: dataObj.radio,
        })
        .then((res) => {
          if (res.code == 0) {
            dataObj.weeksList = res.data;
            dataObj.weekValue = res.data[res.data.length - 1].id;
            getWeekData();
          }
        });
    };
    assignmentData();
    /**
     * 页码change
     */
    let pageChange = (index) => {
      assignmentData();
    };
    let pageChange1 = () => {
      getGridData();
    };
    /**
     * 显示积分弹框
     */
    let operate = (obj, num) => {
      dataObj.dialogFormVisible = true;
      if (num === 1) {
        dataObj.title = "增加";
        dataObj.url = "/api/v1/reward/increase";
      } else {
        dataObj.title = "扣除";
        dataObj.url = "/api/v1/reward/decrease";
      }
      dataObj.student_name = obj.student_name;
      dataObj.balance = obj.balance;
      dataObj.user_id = obj.user_id;
    };

    /**
     * 取消增加或扣除积分
     */
    let cancel = (formRef) => {
      dataObj.dialogFormVisible = false;
      if (!formRef) return;
      formRef.resetFields();
    };
    /**
     * 关闭弹窗
     */
    let handleClose = () => {
      dataObj.dialogFormVisible = false;
      formRef.value.resetFields(); //清空表单校验规则
    };

    /**
     * 增加或扣除积分接口
     */
    let sure = (formRef) => {
      if (!formRef) return;
      formRef.validate((valid, fields) => {
        if (valid) {
          if (
            dataObj.url === "/api/v1/reward/decrease" &&
            dataObj.balance < dataObj.form.score
          ) {
            ElMessage({
              message: "扣除积分不能大于当前积分",
              type: "warning",
            });
          } else {
            proxy.$https
              .post(dataObj.url, {
                user_id: dataObj.user_id,
                amount: Number(dataObj.form.score),
                reason: dataObj.form.reason,
                show_time: dataObj.form.show_time,
              })
              .then((res) => {
                if (!res.code) {
                  ElMessage({
                    message: res.msg,
                    type: "success",
                  });

                  dataObj.dialogFormVisible = false;

                  dataObj.form = {
                    score: "",
                    reason: "",
                    show_time: year + "-" + month + "-" + date,
                  };
                } else {
                  ElMessage({
                    message: res.msg,
                    type: "warning",
                  });
                }
                assignmentData();
              });
          }
        } else {
          ElMessage({
            message: "请填写信息",
            type: "warning",
          });
        }
      });
    };
    /**
     * 详情弹框
     */
    let toDetail = (obj) => {
      dataObj.gridData = [];
      dataObj.user_id = obj.user_id;
      dataObj.activeName = "学情";
      getWeeksList();
      getGridData();
      dataObj.dialogTableVisible = true;
    };
    let getGridData = () => {
      proxy.$https
        .get("/api/v1/rewards", {
          user_id: dataObj.user_id,
          page: dataObj.currentPage1,
          type: dataObj.value,
        })
        .then((res) => {
          if (!res.code) {
            dataObj.detail_total = res.data.total;
            dataObj.detail_balance = res.data.balance;
            dataObj.userName = res.data.student.name;
            dataObj.gridData = res.data.rewards.data;
            dataObj.tableCount1 = res.data.rewards.total;
          }
        });
    };
    /**
     * 详情条件筛选
     */
    let scoreChange = (e) => {
      getGridData();
    };
    let weekChange = () => {
      getWeekData();
    };
    /**
     * 详情弹框关闭
     */
    let tableClose = () => {
      dataObj.dialogTableVisible = false;
      dataObj.value = 1;
    };
    return {
      ...toRefs(dataObj),
      pageChange: pageChange,
      operate: operate,
      toDetail: toDetail,
      cancel: cancel,
      sure: sure,
      formRef: formRef,
      handleClose: handleClose,
      scoreChange: scoreChange,
      tableClose: tableClose,
      weekChange: weekChange,
      pageChange1: pageChange1,
    };
  },
};
</script>
<style scoped lang="scss">
.leads {
  width: 100%;
  height: 100%;
  background: #f7f9fa;
  padding: 20px;
  box-sizing: border-box;
  .serBox {
    width: 100%;
    padding-bottom: 10px;
    overflow: hidden;
    background: #fff;
    margin-bottom: 10px;
  }
  .tableConter {
    clear: both;
    height: auto;
    background: #ffffff;
    padding: 20px 24px;
    .active {
      color: #88a3f1;
      cursor: pointer;
    }
  }
  .personal_info {
    height: 35px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    span {
      font-size: 14px;
      margin-right: 40px;
    }
  }
}
</style>
<style  lang="scss">
.classes,
.teachers {
  .cell {
    display: flex;
    flex-direction: column;
  }
}
</style>